package com.efounder.frame.activity.manager;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;

import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.activity.EFAppAccountMainActivity;
import com.efounder.frame.manager.AppAccountResDownloader;
import com.efounder.frame.utils.Constants;
import com.efounder.frame.utils.EFAppAccountFormUtils;
import com.efounder.frame.utils.EFAppAccountUtils;
import com.efounder.frame.utils.NetStateBroadcastReceiver;
import com.efounder.mobilemanager.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import static com.efounder.frame.utils.Constants.KEY_SETTING_PUBLIC_NUMBER_MAIN_DATA_DOWN_URL;

/**
 * Created by XinQing on 2016/10/19.c
 * EFAppAccountMainActivity 下载管理类
 */
public class EFAppAccountMainActivityDownloadManager {
    private EFAppAccountMainActivity activity;
    private ProgressDialog progressDialog;
    private AppAccountResDownloader appAccountResDownloader;

    public EFAppAccountMainActivityDownloadManager(EFAppAccountMainActivity activity) {
        this.activity = activity;
        int appAccountID = activity.getIntent().getIntExtra("id", 0);
        appAccountResDownloader = new AppAccountResDownloader(activity, appAccountID);
    }

    public interface CheckUrlListener {
        public void onStart();

        public void onSuccess();

        public void onFail();
    }

    /**
     * 检测下载应用号资源文件连接是否可用
     *
     * @param listener
     */
    public void checkUrl(final CheckUrlListener listener) {
        String loginType = EnvironmentVariable.getProperty("LoginType");
        if (null != loginType && loginType.equals("0")) {
            appAccountResDownloader.checkAppAccountResVersion(true, new AppAccountResDownloader.CheckResVerionListener() {
                @Override
                public void onResultVersion(String version, String url) {
                    startCheckUrl(listener);
                }
            });
        } else {
            startCheckUrl(listener);
        }
    }

    private void startCheckUrl(final CheckUrlListener listener) {
        new AsyncTask<String, Integer, String>() {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                listener.onStart();
            }

            @Override
            protected String doInBackground(String... params) {
                String flag = null;
                URL urlLink;
                try {
                    urlLink = new URL(appAccountResDownloader.getDownloadResURL());
                    InputStream in = urlLink.openStream();
                    flag = "success";
                    Log.w("-----", "连接可用");
                } catch (Exception e) {
                    Log.w("-----", "连接打不开!");
                    urlLink = null;
                    flag = "fail";
                }
                return flag;
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                if ("success".equals(s)) {
                    listener.onSuccess();
                } else {
                    listener.onFail();
                }
            }
        }.execute();
    }

    /**
     * 下载应用号资源文件
     *
     * @param listener
     */
    public void downloadResource(AppAccountResDownloader.DownloadAppAccountResourceListener listener) {
        appAccountResDownloader.downloadResource(listener);
    }

    /**
     * 下载主数据
     *
     * @param handler
     */
    public void downloadMainDataAsync(final Handler handler) {
        new AsyncTask<String, Integer, String>() {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                progressDialog = new ProgressDialog(activity);
                progressDialog.setMessage("正在加载数据...");
                progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                progressDialog.setCancelable(true);
                progressDialog.show();
            }

            @Override
            protected String doInBackground(String... params) {
                return downloadMainData();
            }

            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);
                progressDialog.dismiss();
                if ("success".equals(result)) {
                    handler.sendEmptyMessage(3);
                } else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                    if (!NetStateBroadcastReceiver.isNetActive()) {//如果没有网络
                        builder.setMessage("请检查网络是否连接");
                    } else {
                        builder.setMessage("下载主数据失败，请联系管理员\n错误信息：" + result);
                    }
                    builder.setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            activity.finish();
                        }
                    });
                    builder.create().show();
                }

            }
        }.execute();

    }

    /**
     * 下载主数据
     *
     * @return
     */
    private String downloadMainData() {
        String urlStr = EnvironmentVariable.getProperty(KEY_SETTING_PUBLIC_NUMBER_MAIN_DATA_DOWN_URL);
        urlStr += EnvironmentVariable.getProperty(Constants.CHAT_USER_ID);
//        urlStr += "lugy";
        try {
            /*
             * 通过URL取得HttpURLConnection
             * 要网络连接成功，需在AndroidMainfest.xml中进行权限配置
             * <uses-permission android:name="android.permission.INTERNET" />
             */
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //取得inputStream，并进行读取
            InputStream input = conn.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(input));
            String line = null;
            StringBuffer stringBuffer = new StringBuffer();
            while ((line = in.readLine()) != null) {
                stringBuffer.append(line);
            }
            in.close();
            //判断是否是返回错误数据数据
            try {
                JSONObject jsonObjectError = new JSONObject(stringBuffer.toString());
                if (jsonObjectError.has("F_SFCG") && "0".equals(jsonObjectError.get("F_SFCG"))) {//返回了错误信息
                    String errorMessage = null;
                    if (jsonObjectError.has("F_MESSAGE")) {
                        errorMessage = jsonObjectError.getString("F_MESSAGE");
                    } else {
                        errorMessage = "fail";
                    }
                    return errorMessage;//fail
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            //没有返回错误信息，保存主数据
            EFAppAccountFormUtils.saveMainData(stringBuffer.toString(), EFAppAccountUtils.getAppAccountID());
        } catch (Exception e) {
            e.printStackTrace();
            return "请求主数据接口失败，url=" + urlStr;//fail
        }
        return "success";
    }


}
